<template>
  <div class="complete-info-container">
    <el-card class="complete-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><UserFilled /></el-icon>
          <span>完善个人信息</span>
        </div>
        <p class="header-tip">
          <el-icon><InfoFilled /></el-icon>
          为了更好地使用系统，请完善您的个人信息和家长信息
        </p>
      </template>

      <el-steps :active="currentStep" finish-status="success" align-center class="steps">
        <el-step title="基本信息" icon="User" />
        <el-step title="绑定家长" icon="UserFilled" />
      </el-steps>

      <el-form
        v-if="currentStep === 0"
        :model="basicForm"
        :rules="basicRules"
        ref="basicFormRef"
        label-width="100px"
        class="info-form"
      >
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="`/api/file/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="{ 'satoken': token }"
          >
            <img v-if="basicForm.avatar" :src="basicForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="证件照">
          <el-upload
            class="avatar-uploader"
            :action="`/api/file/upload`"
            :show-file-list="false"
            :on-success="handleIdPhotoSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="{ 'satoken': token }"
          >
            <img v-if="basicForm.idPhoto" :src="basicForm.idPhoto" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="basicForm.phone" placeholder="请输入联系电话" clearable />
        </el-form-item>

        <el-form-item label="家庭住址" prop="address">
          <el-input
            v-model="basicForm.address"
            type="textarea"
            :rows="3"
            placeholder="请输入家庭住址"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="nextStep" size="large">
            下一步
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </el-form-item>
      </el-form>

      <el-form
        v-if="currentStep === 1"
        :model="parentForm"
        :rules="parentRules"
        ref="parentFormRef"
        label-width="100px"
        class="info-form"
      >
        <el-divider content-position="left">
          <el-icon><Male /></el-icon>
          父亲信息
        </el-divider>

        <el-form-item label="父亲姓名" prop="fatherName">
          <el-input v-model="parentForm.fatherName" placeholder="请输入父亲姓名" clearable />
        </el-form-item>

        <el-form-item label="父亲手机号" prop="fatherPhone">
          <el-input v-model="parentForm.fatherPhone" placeholder="请输入父亲手机号（用于登录）" clearable />
        </el-form-item>

        <el-divider content-position="left">
          <el-icon><Female /></el-icon>
          母亲信息
        </el-divider>

        <el-form-item label="母亲姓名" prop="motherName">
          <el-input v-model="parentForm.motherName" placeholder="请输入母亲姓名" clearable />
        </el-form-item>

        <el-form-item label="母亲手机号" prop="motherPhone">
          <el-input v-model="parentForm.motherPhone" placeholder="请输入母亲手机号（用于登录）" clearable />
        </el-form-item>

        <el-alert
          title="温馨提示"
          type="info"
          :closable="false"
          show-icon
          class="tip-alert"
        >
          <p style="margin: 0;">
            • 家长手机号将作为登录账号，初始密码为 123456<br>
            • 可以只填写一方家长信息，也可以都填写<br>
            • 家长登录后可以查看您的学习情况
          </p>
        </el-alert>

        <el-form-item>
          <el-button @click="prevStep" size="large">
            <el-icon><ArrowLeft /></el-icon>
            上一步
          </el-button>
          <el-button type="primary" @click="submitAllInfo" :loading="loading" size="large">
            <el-icon><Check /></el-icon>
            完成
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  UserFilled,
  InfoFilled,
  User,
  Plus,
  ArrowRight,
  ArrowLeft,
  Check,
  Male,
  Female
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { updateMyProfile, bindParents } from '@/api/student'

const router = useRouter()
const userStore = useUserStore()
const token = ref(localStorage.getItem('token') || '')

const currentStep = ref(0)
const loading = ref(false)
const basicFormRef = ref<FormInstance>()
const parentFormRef = ref<FormInstance>()

const basicForm = reactive({
  avatar: '',
  idPhoto: '',
  phone: '',
  address: ''
})

const parentForm = reactive({
  fatherName: '',
  fatherPhone: '',
  motherName: '',
  motherPhone: ''
})

// 基本信息验证规则
const basicRules: FormRules = {
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 家长信息验证规则
const parentRules: FormRules = {
  fatherPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  motherPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 上传头像成功
const handleAvatarSuccess = (response: any) => {
  if (response.code === 200 && response.data) {
    // response.data 是 FileInfoVO 对象，需要提取 fileUrl
    basicForm.avatar = response.data.fileUrl || response.data
    ElMessage.success('头像上传成功')
  }
}

// 上传证件照成功
const handleIdPhotoSuccess = (response: any) => {
  if (response.code === 200 && response.data) {
    // response.data 是 FileInfoVO 对象，需要提取 fileUrl
    basicForm.idPhoto = response.data.fileUrl || response.data
    ElMessage.success('证件照上传成功')
  }
}

// 上传前的检查
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

// 下一步
const nextStep = async () => {
  if (!basicFormRef.value) return

  await basicFormRef.value.validate(async (valid) => {
    if (valid) {
      currentStep.value = 1
    }
  })
}

// 上一步
const prevStep = () => {
  currentStep.value = 0
}

// 提交所有信息
const submitAllInfo = async () => {
  if (!parentFormRef.value) return

  // 检查是否至少填写了一方家长信息
  const hasFather = parentForm.fatherName && parentForm.fatherPhone
  const hasMother = parentForm.motherName && parentForm.motherPhone

  if (!hasFather && !hasMother) {
    ElMessage.warning('请至少填写一方家长信息')
    return
  }

  await parentFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 1. 更新基本信息（头像、证件照、电话、地址）
        await updateMyProfile(basicForm)

        // 2. 绑定家长（父母姓名和手机号）
        await bindParents(parentForm)

        ElMessage.success('信息完善成功！')

        // 3. 更新store
        if (userStore.userInfo) {
          userStore.userInfo.infoCompleted = 1
          localStorage.setItem('userInfo', JSON.stringify(userStore.userInfo))
        }

        // 4. 跳转到首页
        setTimeout(() => {
          router.push('/student/dashboard')
        }, 1500)
      } catch (error: any) {
        ElMessage.error(error.response?.data?.msg || '操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  // 如果已经完善信息，跳转到首页
  if (userStore.userInfo?.infoCompleted === 1) {
    router.push('/student/dashboard')
  }
})
</script>

<style scoped lang="scss">
.complete-info-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;

  .complete-card {
    width: 100%;
    max-width: 700px;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

    :deep(.el-card__header) {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-bottom: none;
      padding: 24px;
    }

    .card-header {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 600;

      .header-icon {
        font-size: 24px;
        margin-right: 12px;
      }
    }

    .header-tip {
      margin-top: 12px;
      margin-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 8px;
      color: rgba(255, 255, 255, 0.9);
    }

    :deep(.el-card__body) {
      padding: 32px;
    }

    .steps {
      margin-bottom: 40px;
    }

    .info-form {
      .avatar-uploader {
        :deep(.el-upload) {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          transition: all 0.3s;

          &:hover {
            border-color: #409eff;
          }
        }

        .avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: 120px;
          height: 120px;
          line-height: 120px;
          text-align: center;
        }

        .avatar {
          width: 120px;
          height: 120px;
          display: block;
          object-fit: cover;
        }
      }

      .tip-alert {
        margin-bottom: 20px;
        
        :deep(.el-alert__description) {
          font-size: 14px;
          line-height: 1.8;
        }
      }

      :deep(.el-button) {
        height: 46px;
        font-size: 16px;
        padding: 0 40px;
        border-radius: 8px;
      }

      :deep(.el-form-item) {
        margin-bottom: 24px;
      }

      :deep(.el-divider) {
        margin: 30px 0 20px 0;
        
        .el-divider__text {
          font-size: 16px;
          font-weight: 500;
        }
      }
    }
  }
}
</style>

